//
//  UserInfoFirstController.m
//  CoolTennisBall
//
//  Created by wenshl on 15/12/22.
//  Copyright © 2015年 CoolLang. All rights reserved.
//

#import "UserInfoFirstController.h"
#import "BirthViewController.h"
#import "ButtonCell.h"
#import "HeightViewController.h"
#import "LabelCell.h"
#import "PhotoActionSheetViewController.h"
#import "SportAgeViewController.h"
#import "UIImage+TennisTintColor.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "UIView+SLAnimation.h"
#import "WeightViewController.h"
#import "MBProgressHUD+Add.h"

static NSString * const kLabelCell = @"labelCell";
static NSString * const kButtonCell = @"buttonCell";
static NSString * const kuserInfoToTabSegue = @"kuserInfoToTabSegue";

@interface UserInfoFirstController ()<UITableViewDelegate,UITableViewDataSource,HeightViewControllerDelegate,WeightViewControllerDelegate,BirthViewControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,BallAgeViewControllerDelegate,HandDelegate,UITextFieldDelegate>

@property (copy, nonatomic) NSString *birthday;
@property (copy, nonatomic) NSString *height;
@property (copy, nonatomic) NSString *weight;
@property (copy, nonatomic) NSString *sportAge;
@property (copy, nonatomic) NSString *hand;
@property (copy, nonatomic) NSString *gender;
@property (assign, nonatomic) BOOL changedHeadIcon;
@property (assign, nonatomic) BOOL defaulted;

@property (weak, nonatomic) IBOutlet UILabel *topTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *topDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *nickNameDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *genderDescriptionLabel;
@property (weak, nonatomic) IBOutlet UIButton *maleButton;
@property (weak, nonatomic) IBOutlet UIButton *femaleButton;
@property (weak, nonatomic) IBOutlet UIButton *saveButton;


@end

@implementation UserInfoFirstController{
    
    __weak IBOutlet NSLayoutConstraint *tableHeightConstrait;
    __weak IBOutlet UIView *cornerView;
    __weak IBOutlet UITableView *userTableView;
    __weak IBOutlet UIView *bordView;
    __weak IBOutlet UITextField *nameTextField;
    __weak IBOutlet UIImageView *canemaImageView;
    
    __weak IBOutlet NSLayoutConstraint *viewLeftConstrait;
    __weak IBOutlet UIView *leftTransView;
    
    __weak IBOutlet UIView *leftTransBottomView;
}

#pragma mark - View LifeCircle / initData

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureLocalization];
    [self initData];
    
    [self configureCornerRidus];
    [self configureCanema];
    tableHeightConstrait.constant = 8 + 215 + 50 + 20;
    
    leftTransView.transform = CGAffineTransformMakeTranslation(-300, -100);
    leftTransBottomView.transform = CGAffineTransformMakeTranslation(-300, -100);

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // 动画
  
    [UIView animateWithDuration:0.5 animations:^{
        tableHeightConstrait.constant = 8;
        leftTransView.transform = CGAffineTransformIdentity;
        leftTransBottomView.transform = CGAffineTransformIdentity;
        [userTableView layoutIfNeeded];
        [self.saveButton layoutIfNeeded];
        [self.view layoutIfNeeded];
    }];
}

- (void)initData {
    _hand = @"1";
    _birthday = @"";
    _sportAge = @"0";
    _height   = @"";
    _weight   = @"";
    _gender   = @"1";
    nameTextField.text = @"";
}

#pragma mark - Localization

- (void)configureLocalization
{
    self.topTitleLabel.text = NSLocalizedString(@"Personal Information", nil);
    self.topDescriptionLabel.text = NSLocalizedString(@"Complete your personal information to customized your exercise plan.", nil);
    self.nickNameDescriptionLabel.text = NSLocalizedString(@"Nickname", nil);
    nameTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"Please Enter", nil) attributes: @{                                                                                                                                    NSForegroundColorAttributeName: [UIColor colorWithWhite:1.0f alpha:0.7f]                                                                                                                                                                                                                                                                        }];
    self.genderDescriptionLabel.text = NSLocalizedString(@"Gender", nil);
    [self.maleButton setTitle:NSLocalizedString(@"Male", nil) forState:UIControlStateNormal];
    [self.femaleButton setTitle:NSLocalizedString(@"Female", nil) forState:UIControlStateNormal];
    [self.saveButton setTitle:NSLocalizedString(@"Save", nil) forState:UIControlStateNormal];
}

#pragma mark - set HeadIcon

- (void)takePhotoByCamera{
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        [MBProgressHUD showTextHUDWithMessage:@"无法获取像机及照片信息" inView:self.view];
        return;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)takePhotoByPhotos{
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        [MBProgressHUD showTextHUDWithMessage:@"无法获取像机及照片信息" inView:self.view];
        return;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)setHeadIcon
{
    __weak typeof(self) weakSelf = self;
    [PhotoActionSheetViewController showInParentViewController:self animationType:DetailViewControllerPresentAnimationTypeUp actionBlock:^(kTapActionButtonType btnType) {
        if (btnType == kTapAlbumButton) {
            [weakSelf takePhotoByPhotos];
        } else  if (btnType == kTapCameraButton) {
            [weakSelf takePhotoByCamera];
        }
    }];
}

#pragma mark - IBAction

- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)saveInfomation:(id)sender {
    
    if (![self checkUserInfo]) {
        return;
    }
    
    if (!_defaulted) {
        FUIAlertView *alertShow = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"Are you the right hander", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"Yes", nil) otherButtonTitles:NSLocalizedString(@"Reselect", nil), nil];
        [alertShow customizeAppearance];
        [alertShow show];
        alertShow.onCancelAction = ^{
            [self uploadHeadIcon];
        };
        
    } else {
        [self uploadHeadIcon];
    }
    
    

    
}

- (void)uploadHeadIcon {
    
    MBProgressHUD *hud = [MBProgressHUD showMessag:NSLocalizedString(@"Uploading data...", nil)  toView:self.view];
    if (_changedHeadIcon) {
        [YFUserApi uploadImageWithRequestType:kUserUploadHeadImage withImage:canemaImageView.image complete:^(NSError *error, NSString *imageUrl) {
            if (error == nil) {
                [self uploadUserInfo:imageUrl completed:^{
                    [hud hideAnimated:YES];
                }];
            } else {
                [hud hideAnimated:YES];
            }
        }];
    } else {
        [self uploadUserInfo:@"" completed:^{
            [hud hideAnimated:YES];
        }];
    }
}

- (void)uploadUserInfo:(NSString *)imageUrl completed:(void(^)())completed {
    
  [YFUserApi requestSvaeUserInfoWithUserName:nameTextField.text birthday:_birthday isMale:_gender height:_height weight:_weight signature:@"" SportAge:_sportAge Address:@"" Hand:_hand RaketBrand:@"" StartTennisYear:@"" Level:@"" complete:^(NSError *error) {
        if (completed) {
            completed();
        }
        if (error == nil) {
            [self operationUserInfoItem:imageUrl];
            [self performSegueWithIdentifier:kuserInfoToTabSegue sender:nil];
            [DataModel setAutoLogin:YES];
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            NSLog(@"%@",error);
        }
    }];

}

- (IBAction)selectGender:(UIButton *)sender {
    
    for (UIView *view in sender.superview.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)view;
            btn.selected  = NO;
        }
    }
    sender.selected = YES;
    _gender = sender.tag == 101 ?  @"1" : @"0";
}



#pragma mark - showErrorInfo/reminder

- (void)showError:(NSString *)error{
    
    FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:error delegate:nil cancelButtonTitle:NSLocalizedString(@"Yes", nil) otherButtonTitles:nil];
    [alertView customizeAppearance];
    [alertView show];
}

- (void)showShortInfo:(NSString *)info{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [hud showTextHUDWithMessage:info inView:self.view];
}

#pragma mark - Private Method


- (void)configureCanema {
    
    cornerView.userInteractionEnabled = YES;
    [cornerView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(setHeadIcon)]];
}

- (void)configureCornerRidus {
    
    bordView.layer.borderWidth = 3.0;
    bordView.backgroundColor   = [UIColor colorWithHex:0xffffff alpha:0.7];
    bordView.layer.borderColor = [UIColor colorWithHex:0x25c9ad alpha:0.3].CGColor;
    cornerView.layer.cornerRadius= cornerView.bounds.size.width / 2;
    bordView.layer.cornerRadius = bordView.bounds.size.width / 2;
    self.saveButton.layer.cornerRadius= 5.0;
}

- (BOOL)checkUserInfo {

    if (nameTextField.text.length == 0) {
        [self showShortInfo:NSLocalizedString(@"Please enter nickname", nil)];
        return NO;
    }
    
    if ([_birthday isEqualToString:@""]) {
        [self showShortInfo:NSLocalizedString(@"Please choose birthday", nil)];
        return NO;
    }
    
    if ([_height isEqualToString:@""]) {
        [self showShortInfo:NSLocalizedString(@"Please choose height", nil)];
        return NO;

    }
    
    if ([_weight isEqualToString:@""]) {
        [self showShortInfo:NSLocalizedString(@"Please choose weight", nil)];
        return NO;
    }

//    if ([_sportAge isEqualToString:@""]) {
//        [self showShortInfo:NSLocalizedString(@"Please choose training years", nil)];
//        return NO;
//    }

    return YES;
    
}

- (void)showHeightViewController{
    HeightViewController *viewController = [[HeightViewController alloc] initWithNibName:@"HeightViewController" bundle:nil];
    viewController.delegate = self;
    [viewController presentInParentViewController:self animationType:DetailViewControllerPresentAnimationTypeUp];
}

- (void)showWeightViewContoller{
    WeightViewController *viewController = [[WeightViewController alloc] initWithNibName:@"WeightViewController" bundle:nil];
    viewController.delegate = self;
    [viewController presentInParentViewController:self animationType:DetailViewControllerPresentAnimationTypeUp];
}

- (void)showBirthdayViewController{
    BirthViewController *viewController = [[BirthViewController alloc] initWithNibName:@"BirthViewController" bundle:nil];
    viewController.delegate = self;
    viewController.birth = @"1970-07-19";
    [viewController presentInParentViewController:self animationType:DetailViewControllerPresentAnimationTypeUp];
}

- (void)showBallAgePicker
{
    SportAgeViewController *controller = [[SportAgeViewController alloc] initWithNibName:@"SportAgeViewController" bundle:nil];
    controller.delegate = self;
    [controller presentInParentViewController:self animationType:DetailViewControllerPresentAnimationTypeUp];
}



#pragma mark - HandDelegate

- (void)selectedHand:(NSString *)hand {
    _hand = hand;
    _defaulted = YES;
}

#pragma mark - tableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell;
    if (indexPath.row < 3) {
        LabelCell *labelCell = (LabelCell *)[tableView dequeueReusableCellWithIdentifier:kLabelCell];
        [labelCell configureTitle:indexPath];
        return labelCell;
    } else {
        ButtonCell *buttonCell = (ButtonCell *)[tableView dequeueReusableCellWithIdentifier:kButtonCell];
        buttonCell.delegate = self;
        buttonCell.handednessLabel.text = NSLocalizedString(@"Handedness", nil);
        [buttonCell.leftButton setTitle:NSLocalizedString(@"Lefty", nil) forState:UIControlStateNormal];
        [buttonCell.rightButton setTitle:NSLocalizedString(@"Righty", nil) forState:UIControlStateNormal];
        return buttonCell;
    }
    
    return cell;
}


#pragma mark - tableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 1:
            [self showHeightViewController];
            break;
        case 2:
            [self showWeightViewContoller];
            break;
        case 0:
            [self showBirthdayViewController];
            break;
//        case 3:
//            [self showBallAgePicker];
//            break;
        default:
            break;
    }

}

#pragma mark - UIImagePickerViewDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    canemaImageView.image = info[UIImagePickerControllerOriginalImage];
    canemaImageView.layer.cornerRadius = 71 / 2;
    canemaImageView.layer.masksToBounds= YES;
    _changedHeadIcon = YES;
    [picker dismissViewControllerAnimated:YES completion:nil];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
}

#pragma mark - UserInfo set Delegate

- (void)heightViewController:(HeightViewController *)controller didSelectHeight:(NSString *)heightStr{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
    LabelCell *cell = [userTableView cellForRowAtIndexPath:indexPath];
    cell.height = heightStr;
    _height = heightStr;
}

- (void)weightViewController:(WeightViewController *)controller didSelectWeight:(NSString *)weightStr{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
    LabelCell *cell = [userTableView cellForRowAtIndexPath:indexPath];
    cell.weight = weightStr;
    _weight = weightStr;
}


- (void)birthViewController:(BirthViewController *)controller didSelectBirth:(NSAttributedString *)birthStr{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    LabelCell *cell = [userTableView cellForRowAtIndexPath:indexPath];
    cell.date = birthStr;
    _birthday = birthStr.string;
}

- (void)ballAgeViewController:(SportAgeViewController *)controller didSelectRowDataString:(NSString *)dataRowString index:(NSInteger)index
{
   // NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
//    LabelCell *cell = [userTableView cellForRowAtIndexPath:indexPath];
//    cell.ballAge = dataRowString;
    //_sportAge = [@(index) stringValue];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;

}


#pragma mark - DBOperation

- (void)operationUserInfoItem:(NSString *)headIconUrl{
    UserInforItem *item = [User getLastUser].userInforItem;
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm beginWriteTransaction];
    
    item.name = nameTextField.text;
    if (_changedHeadIcon) {
        item.headIconPath = headIconUrl;
    }
    item.birth  = _birthday;
    item.height = _height;
    item.weight = _weight;
    item.genderType = [_gender isEqualToString:@"1"] ? GenderTypeMale : GenderTypeFemale;
    item.hand  = [_hand integerValue];
    item.ballAge = _sportAge;
    [realm commitWriteTransaction];
    
}

- (BOOL)fd_interactivePopDisabled{
    return YES;
}


@end
